//
//  ClassCircleTableViewCell.swift
//  BellManage
//
//  Created by Bestsch on 16/6/7.
//  Copyright © 2016年 wsl. All rights reserved.
//

import UIKit

class ClassCircleTableViewCell: UITableViewCell,UICollectionViewDelegate,UICollectionViewDataSource,UITableViewDelegate,UITableViewDataSource,CXAlterButtonDelegate {
    
    var bgView,photoBgView: UIView!
    var timeLabel,nameLabel,titleLabel: UILabel!
    var photoCollectionView: UICollectionView!
    var player: AVAudioPlayer!
    var videoImage: UIImageView!
    var userTx: UIImageView!
    var oneImage: PicProgressView!
    var mobilePhone: UILabel!
    var mobileImage: UIImageView!
    
    var praiseLabel: UILabel!
    var tableview: UITableView!
    //    var button: CXAlterButton!
    var share: UIImageView!
    
    var dic: JSON!
    var praiseName = ""//点赞的人
    var comment = NSMutableArray()//评论内容
    var commentid = NSMutableArray()//评论的id
    var commentSendid = NSMutableArray()//评论人的id
    
    var apiUrl: String!
    
    
    let collectionIdentifier = "PicCollectionViewCellIdentifier"
    let imageArray = NSMutableArray()
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    init(dictionary: JSON, apiUrl: String!, reuseIdentifier: String?) {
        self.apiUrl = apiUrl
        self.dic = dictionary
        super.init(style: UITableViewCellStyle.default, reuseIdentifier: reuseIdentifier)
        setUp()
    }
    
    /**
     初始化设置各种控件
     */
    func setUp() {
        bgView = UIView.init(frame: CGRect.zero)
        bgView.backgroundColor = UIColor.init(hexString: "f6f6f6", alpha: 1)
        
        titleLabel = UILabel.init(frame: CGRect.zero)
        titleLabel.numberOfLines = 0
        titleLabel.font = UIFont.systemFont(ofSize: 14)
        titleLabel.textColor = UIColor.black
        titleLabel.textAlignment = NSTextAlignment.left
        
        timeLabel = UILabel.init(frame: CGRect.zero)
        timeLabel.font = UIFont.systemFont(ofSize: 14)
        timeLabel.textColor = textlight
        timeLabel.textAlignment = NSTextAlignment.right
        
        nameLabel = UILabel.init(frame: CGRect.zero)
        //        nameLabel.font = UIFont.systemFontOfSize(16)
        nameLabel.textColor = UIColor.init(red: 0.310, green: 0.376, blue: 0.510, alpha: 1.00)
        nameLabel.textAlignment = NSTextAlignment.left
        
        photoCollectionView = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: photoFlowLayout.init())
        photoCollectionView.backgroundColor = UIColor.white
        photoCollectionView.register(PicCollectionViewCell.self, forCellWithReuseIdentifier: collectionIdentifier)
        photoCollectionView.scrollsToTop = true
        photoCollectionView.delegate = self
        photoCollectionView.dataSource = self
        
        photoBgView = UIView.init(frame: CGRect.zero)
        photoBgView.backgroundColor = UIColor.white
        
        
        videoImage = UIImageView.init(frame: CGRect.zero)
        videoImage.image = UIImage.init(named: "vdimg")
        videoImage.contentMode = UIViewContentMode.center
        videoImage.clipsToBounds = true
        videoImage.isUserInteractionEnabled = true
        let videoRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(ClassWorkTableViewCell.playVideo))
        videoImage.addGestureRecognizer(videoRecognizer)
        
        userTx = UIImageView.init(frame: CGRect.zero)
        
        mobilePhone = UILabel.init(frame: CGRect.zero)
        mobilePhone.font = UIFont.systemFont(ofSize: 14)
        mobilePhone.textColor = UIColor.lightGray
        mobilePhone.textAlignment = NSTextAlignment.left
        
        mobileImage = UIImageView.init(frame: CGRect.zero)
        
        oneImage = PicProgressView.init(frame: CGRect.zero)
        oneImage.isUserInteractionEnabled = true
        let showImage = UITapGestureRecognizer.init(target: self, action: #selector(ClassWorkTableViewCell.showImage))
        oneImage.addGestureRecognizer(showImage)
        
//        button = CXAlterButton.init(image: UIImage.init(named: "shareall"), highLightImage: UIImage.init(named: "shareall"), direction: DirectionType.Left)
//        let item1: CXAlterItemButton = CXAlterItemButton.init(image: UIImage.init(named: "xinkong")!, with: "点赞")
//        let item2: CXAlterItemButton = CXAlterItemButton.init(image: UIImage.init(named: "talk"), with: "评论")
//        let item3: CXAlterItemButton = CXAlterItemButton.init(image: UIImage.init(named: "share"), with: "分享")
//        button.addButtonItems([item1,item2,item3])
//        button.delegate = self;
        
        share = UIImageView.init(frame: CGRect.zero)
        share.image = UIImage.init(named: "sharehui")
        share.isUserInteractionEnabled = true
        let shareClick = UITapGestureRecognizer.init(target: self, action: #selector(ClassCircleTableViewCell.shareClick))
        share.addGestureRecognizer(shareClick)
        
        
        praiseLabel = UILabel.init(frame: CGRect.zero)
        praiseLabel.font = UIFont.systemFont(ofSize: 14)
        praiseLabel.numberOfLines = 0
        praiseLabel.textColor = barColor
        
        tableview = UITableView.init(frame: CGRect.zero)
        tableview.scrollsToTop = false
        tableview.isScrollEnabled = false
        tableview.delegate = self
        tableview.dataSource = self
        tableview.separatorStyle = UITableViewCellSeparatorStyle.none
        
        
        var title = dic["title"].stringValue
        title = title.removingPercentEncoding!
        let time = dic["EditDate"].stringValue
        print("EditDate = \(time)")
        let mobile = dic["Modular"].stringValue
        let imageUrl = dic["url"].stringValue
        var username = dic["TeaName"].stringValue
        var userphoto = dic["userphoto"].stringValue
        let classname = dic["classname"].stringValue
        var usertype = dic["UserType"].stringValue
        usertype = usertype.replacingOccurrences(of: " ", with: "")
        let prlist = dic["prlist"]
        
        if prlist.count != 0 {
            for i in 0..<prlist.count {
                let dic = prlist[i]
                var pname = dic["TeaName"].stringValue
                let pType = dic["UserType"].stringValue
                if pType == "T" {
                    pname = "\(pname)老师"
                }else{
                    pname = "\(pname)家长"
                }
                praiseName = "\(praiseName),\(pname)"
            }
        }
        if praiseName.characters.count > 0{
            praiseName = (praiseName as NSString).substring(from: 1)
            praiseName = "     \(praiseName)"
            
        }
        
        let aclist = dic["aclist"]
        if aclist.count != 0 {
            for i in 0..<aclist.count {
                let dic = aclist[i]
                let serid = dic["SerID"].stringValue
                let userid = dic["UserSerID"].stringValue
                var username = dic["UserName"].stringValue
                username = username.replacingOccurrences(of: " ", with: "")
                let userType = dic["UserType"].stringValue
                var msg = dic["ReMsg"].stringValue
                msg = msg.removingPercentEncoding!
                var commentStr = ""
                commentStr = "\(username): \(msg)"
                if userType == "T" {
                    commentStr = "\(username)老师: \(msg)"
                }else{
                    commentStr = "\(username)家长: \(msg)"
                }
                comment.add(commentStr)
                commentid.add(serid)
                commentSendid.add(userid)
                
                let aclist1 = dic["aclist1"]
                if aclist1.count != 0 {
                    for i in 0..<aclist1.count {
                        let dic = aclist1[i]
                        let serid = dic["UserID"].stringValue
                        var username = dic["UserName"].stringValue
                        username = username.replacingOccurrences(of: " ", with: "")
                        let usertype = dic["UserType"].stringValue
                        if usertype == "T" {
                            username = "\(username)老师"
                        }else{
                            username = "\(username)家长"
                        }
                        let ruserid = dic["ReUserID"].stringValue
                        var rusername = dic["ReUsername"].stringValue
                        rusername = rusername.replacingOccurrences(of: " ", with: "")
                        let rusertype = dic["ReUserType"].stringValue
                        if rusertype == "T" {
                            rusername = "\(rusername)老师"
                        }else{
                            rusername = "\(rusername)家长"
                        }
                        var msg = dic["ReplyMemo"].stringValue
                        msg = msg.removingPercentEncoding!
                        let commentStr = "\(username)回复\(rusername): \(msg)"
                        comment.add(commentStr)
                        commentid.add(serid)
                        commentSendid.add(ruserid)
                    }
                }
            }
        }
        
        
        
        titleLabel.text = title
        timeLabel.text = getTimeSinceNow(time).replacingOccurrences(of: ".", with: "")
//        timeLabel.text = getTimeIntervalSinceNow(time)
        //        username = "\(username) \(classname)"
        if usertype == "T" {
            username = "\(username)老师"
        }else{
            username = "\(username)家长"
        }
        let st2 = NSMutableAttributedString.init(string: "\(username) \(classname)")
        st2.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 16), range: NSMakeRange(0, username.characters.count))
        st2.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 14), range: NSMakeRange(username.characters.count, st2.length - username.characters.count))
        nameLabel.attributedText = st2
        userphoto = userphoto.replacingOccurrences(of: "../..", with: "")
        userTx.sd_setImage(with: URL.init(string: server + userphoto), placeholderImage: UIImage.init(named: "touxiangm"))
        
        self.contentView.addSubview(bgView)
        self.contentView.addSubview(userTx)
        self.contentView.addSubview(nameLabel)
        
        self.contentView.addSubview(titleLabel)
        self.contentView.addSubview(photoBgView)
        self.contentView.addSubview(timeLabel)
        self.contentView.addSubview(mobileImage)
        self.contentView.addSubview(mobilePhone)
        #if EDUMANAGE || HSEDUMANAGE || TXEDUMANAGE
            self.contentView.addSubview(share)
        #endif
        
        if praiseName.characters.count != 0 {
            let imageView: UIImageView = UIImageView.init(frame: CGRect(x: 0, y: 0, width: 15, height: 15))
            imageView.image = UIImage.init(named: "yeszan")
            praiseLabel.addSubview(imageView)
            self.contentView.addSubview(praiseLabel)
            praiseLabel.text = praiseName
        }
        if commentid.count != 0 {
            self.contentView.addSubview(tableview)
        }
        
        var height: CGFloat = 0.0
        
        
        let array = imageUrl.components(separatedBy: "|") as NSArray
        if array.count == 1 {
            
            let photo = imageUrl.replacingOccurrences(of: "../..", with: "")
            if photo.characters.count == 0 || photo == "alse" {
                
            }else if photo.hasSuffix(".mp4") {
                self.contentView.addSubview(videoImage)
            }else {
                self.contentView.addSubview(oneImage)
                
                var imageurl = server + priImg + photo + "&width=400&mode=W"
                
                let user = getUserPojo()
                if self.apiUrl.characters.count != 0 {
                    imageurl = imageurl.replacingOccurrences(of: server, with: user.doname).replacingOccurrences(of: "", with: "")
                }
                
                oneImage.imageUrl = imageurl
            }
            
        }else {
            self.contentView.addSubview(photoCollectionView)
            imageArray.addObjects(from: array as [AnyObject])
        }
        height = getPhotoCollectionHeight(array)
        
        /// 头像，间隔，上下间隔，时间，图片等，内容
        
        var cellHeight: CGFloat = 10.0+35+(10+getLabelHeight(title, font: UIFont.systemFont(ofSize: 14) , wigth: screenW - 60))+(10+height)+(10+30)+5
        
        if praiseName.characters.count > 0 {
            cellHeight += getLabelHeight(praiseName, font: UIFont.systemFont(ofSize: 14) , wigth: screenW - 40) + 5
        }
        if comment.count > 0 {
            cellHeight += 5 + getCommentTableHeight(comment)
        }
        mobilePhone.text = mobile
        if mobile.contains("iPhone") {
            mobileImage.image = UIImage.init(named: "ios")
        }else if mobile.contains("PC"){
            mobileImage.image = UIImage.init(named: "pc")
            mobilePhone.text = "电脑客户端"
        }else{
            mobileImage.image = UIImage.init(named: "mobile")
        }
        
        bgView.frame = CGRect(x: 10, y: 10, width: screenW - 20, height: cellHeight - 20)
        bgView.layer.cornerRadius = 4;
        bgView.layer.shadowOffset = CGSize(width: 0, height: 1);  // 设置阴影的偏移量
        bgView.layer.shadowRadius = 2.0;  // 设置阴影的半径
        bgView.layer.shadowColor = UIColor.lightGray.cgColor; // 设置阴影的颜色为黑色
        bgView.layer.shadowOpacity = 0.8; // 设置阴影的不透明度
        
        userTx.frame = CGRect(x: bgView.frame.minX + 10, y: bgView.frame.minY + 5, width: 30, height: 30)
        userTx.layer.masksToBounds = true
        userTx.layer.cornerRadius = 15
        
        nameLabel.frame = CGRect(x: userTx.frame.maxX + 10, y: userTx.frame.minY, width: screenW/2, height: 30);
        timeLabel.frame = CGRect(x: bgView.frame.maxX - 100 , y: userTx.frame.minY,width: 90, height: 30);
        //类型
        //        typeMark.frame = CGRectMake(CGRectGetMaxX(bgView.frame)-15, CGRectGetMinY(bgView.frame) + 10, 2, 20);
        //        contentType.frame = CGRectMake(CGRectGetMinX(typeMark.frame)-110, CGRectGetMinY(bgView.frame) + 5, 100, 30);
        
        
        //title标题
        titleLabel.frame = CGRect(x: userTx.frame.minX+10, y: userTx.frame.maxY+10, width: screenW - 60, height: getLabelHeight(title, font: UIFont.systemFont(ofSize: 14) , wigth: screenW - 60));
        
        photoBgView.frame = CGRect(x: bgView.frame.minX, y: titleLabel.frame.maxY+10, width: bgView.frame.width, height: height);
        
        videoImage.frame = CGRect(x: photoBgView.frame.minX+5, y: photoBgView.frame.minY+5, width: photoBgView.frame.width-10,height: 140);
        
        oneImage.frame = CGRect(x: photoBgView.frame.minX+5, y: photoBgView.frame.minY+5, width: photoBgView.frame.width-10, height: photoBgView.frame.height-10);
        
        photoCollectionView.frame = CGRect(x: photoBgView.frame.minX+5, y: photoBgView.frame.minY+5, width: photoBgView.frame.width-10, height: self.photoBgView.frame.height-10);
        mobileImage.frame = CGRect(x: bgView.frame.minX+10, y: photoBgView.frame.maxY + 7.5, width: 15, height: 15)
        mobilePhone.frame = CGRect(x: mobileImage.frame.maxX, y: photoBgView.frame.maxY, width: 100, height: 30)
        //        button.buttonCenter = CGPointMake(CGRectGetMaxX(self.bgView.frame)-30, CGRectGetMinY(mobilePhone.frame)+2);
        //        button.buttonSize = CGSizeMake(30,22.5);//40,30
        //        button.animationDuration = 0.5;
        share.frame = CGRect(x: bgView.frame.maxX - 30, y: photoBgView.frame.maxY+5, width: 18, height: 20)
        
        praiseLabel.frame = CGRect(x: self.bgView.frame.minX + 10, y: mobilePhone.frame.maxY, width: self.bgView.frame.width - 20, height: getLabelHeight(praiseName, font: UIFont.systemFont(ofSize: 14) , wigth: self.bgView.frame.width - 20))
        tableview.frame = CGRect(x: self.bgView.frame.minX, y: praiseLabel.frame.maxY+5, width: screenW - 20, height: getCommentTableHeight(comment))
        
    }
    
    func shareClick(){
        let serid = self.dic["SerID"].stringValue
        let title = self.dic["title"].stringValue
//        let sendUid = self.dic.objectForKey("userid") as! String
        let imageUrl = dic["url"].stringValue
        if !imageUrl.contains(".mp4"){
            let username = dic["TeaName"].stringValue
            NotificationCenter.default.post(name: Notification.Name(rawValue: "shareWorkNotification"), object: nil, userInfo: ["serid" : serid, "title" : title, "TeaName" : username, "imageUrl" : imageUrl])
        }else{
            TSMessage.showNotification(withTitle: "目前只支持图文活动的分享，暂不支持其它类型的活动。谢谢！", type: TSMessageNotificationType.error)
        }
    }
    
    //MARK: - CXAlterButtonDelegate
    
    func alterButton(_ button: CXAlterButton!, clickItemButtonAt index: UInt) {
        let serid = self.dic["SerID"].stringValue
        let title = self.dic["title"].stringValue
        let sendUid = self.dic["userid"].stringValue
        switch index {
        case 0:
            //点赞
            NotificationCenter.default.post(name: Notification.Name(rawValue: "pariseWorkNotification"), object: nil, userInfo: ["serid" : serid, "senduid" : sendUid])
            break
        case 1:
            //评论
            NotificationCenter.default.post(name: Notification.Name(rawValue: "CommentWorkNotification"), object: nil, userInfo: ["serid" : serid, "senduid" : sendUid, "preid" : "0", "typeid" : "1"])
            
            
            break
        case 2:
            //分享
            let imageUrl = dic["url"].stringValue
            if !imageUrl.contains(".mp4"){
                let username = dic["TeaName"].stringValue
                NotificationCenter.default.post(name: Notification.Name(rawValue: "shareWorkNotification"), object: nil, userInfo: ["serid" : serid, "title" : title, "TeaName" : username, "imageUrl" : imageUrl])
            }else{
                TSMessage.showNotification(withTitle: "目前只支持图文活动的分享，暂不支持其它类型的活动。谢谢！", type: TSMessageNotificationType.error)
            }
            
            break
        default:
            break
        }
    }
    
    //MARK: - 照片集的 collectionView
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageArray.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: PicCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionIdentifier, for: indexPath) as! PicCollectionViewCell
        cell.backgroundColor = UIColor.white
        
        var photo = imageArray.object(at: (indexPath as NSIndexPath).row) as! String
        photo = photo.replacingOccurrences(of: "../..", with: "")
        var imageurl = server + priImg + photo + "&width=300&mode=W"
        let user = getUserPojo()
        if self.apiUrl.characters.count != 0 {
            imageurl = imageurl.replacingOccurrences(of: server, with: user.doname).replacingOccurrences(of: "", with: "")
        }
        cell.imageUrl = imageurl
        
        return cell;
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let imageUrl = dic["url"].stringValue
        let index = String((indexPath as NSIndexPath).row)
        NotificationCenter.default.post(name: Notification.Name(rawValue: "showBigImage"), object: nil, userInfo: ["url" : imageUrl, "index" : index])
    }

    /**
     播放视频
     */
    func playVideo() {
        let imageUrl = dic["url"].stringValue
        NotificationCenter.default.post(name: Notification.Name(rawValue: "playvideo"), object: nil, userInfo: ["url" : imageUrl])
    }
    /**
     显示大图
     */
    func showImage() {
        let imageUrl = dic["url"].stringValue
        let index = "0"
        NotificationCenter.default.post(name: Notification.Name(rawValue: "showBigImage"), object: nil, userInfo: ["url" : imageUrl, "index" : index])
    }
    
    //MARK: - 评论的tableView
    
    /**
     评论的tablview
     
     - parameter tableView:
     
     - returns:
     */
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return commentid.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return getLabelHeight(comment.object(at: (indexPath as NSIndexPath).row) as! String, font: UIFont.systemFont(ofSize: 14) , wigth: screenW - 40) + 5
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "CommentTableViewCellIdentifier";
        let cell: CommentTableViewCell = CommentTableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: cellIdentifier)
        cell.backgroundColor = UIColor.init(hexString: "f9f9f9", alpha: 1)
        cell.selectionStyle = UITableViewCellSelectionStyle.none;
        
        let str = comment.object(at: (indexPath as NSIndexPath).row) as! String
        let arr:NSArray = str.components(separatedBy: ":") as NSArray
        let name = arr.object(at: 0) as! String
        let arrname: NSArray = name.components(separatedBy: "回复") as NSArray
        let str1 = NSMutableAttributedString.init(string: str)
        if arrname.count == 1 {
            let length = name.characters.count
            str1.addAttribute(NSForegroundColorAttributeName, value: UIColor.init(red: 0.310, green: 0.376, blue: 0.510, alpha: 1.00), range: NSMakeRange(0, length))
            str1.addAttribute(NSForegroundColorAttributeName, value: UIColor.darkText, range: NSMakeRange(length, str.characters.count - length))
            str1.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFont(ofSize: 14) , range: NSMakeRange(0, length))
            str1.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 14) , range: NSMakeRange(length, str.characters.count - length))
        }else if arrname.count == 2 {
            let length = name.characters.count
            let lengthSend = (arrname.object(at: 0) as! String).characters.count
            let lengthReply = (arrname.object(at: 1) as! String).characters.count
            str1.addAttribute(NSForegroundColorAttributeName, value: UIColor.init(red: 0.310, green: 0.376, blue: 0.510, alpha: 1.00), range: NSMakeRange(0, lengthSend))
            str1.addAttribute(NSForegroundColorAttributeName, value: UIColor.darkText, range: NSMakeRange(lengthSend, 2))
            str1.addAttribute(NSForegroundColorAttributeName, value: UIColor.init(red: 0.310, green: 0.376, blue: 0.510, alpha: 1.00), range: NSMakeRange(lengthSend+2,lengthReply))
            str1.addAttribute(NSForegroundColorAttributeName, value: UIColor.darkText, range: NSMakeRange(length,str.characters.count-length))
            
            str1.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFont(ofSize: 14), range: NSMakeRange(0, lengthSend))
            str1.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 14) , range: NSMakeRange(lengthSend, 2))
            str1.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFont(ofSize: 14), range: NSMakeRange(lengthSend+2,lengthReply))
            str1.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 14), range: NSMakeRange(length,str.characters.count-length))
        }
        
        
        cell.commentLabel.frame = CGRect(x: 10, y: 0, width: screenW - 40, height: getLabelHeight(comment.object(at: (indexPath as NSIndexPath).row) as! String, font: UIFont.systemFont(ofSize: 14) , wigth: screenW - 40)+5)
        cell.commentLabel.attributedText = str1
        
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //        //取消选中状态
        //        let serid = self.dic.objectForKey("SerID") as! String
        //        let preid = commentid.objectAtIndex(indexPath.row)
        //        let sendUid = commentSendid.objectAtIndex(indexPath.row)
        //
        //        NSNotificationCenter.defaultCenter().postNotificationName("CommentWorkNotification", object: nil, userInfo: ["serid" : serid, "senduid" : sendUid, "preid" : preid, "typeid" : "2"])
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
        // Configure the view for the selected state
    }
    
}
